//
//  bigPicViewController.m
//  TinyFortune
//
//  Created by lc on 16/5/30.
//  Copyright © 2016年 lc. All rights reserved.
//

#import "bigPicViewController.h"
#import "tintyCell.h"
#import "tinyDataModel.h"
#import "tinyFrameModel.h"
#import "AVFile +  getDictionary.h"
#import "commendModel.h"
#import "commendTableViewCell.h"

@interface bigPicViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>{
    NSDictionary *_dict;
    UITextView *_commendText;
    NSString *_iconUrl;//说说用户头像
    NSString *_username;//说说用户手机号码
    AVObject *_MessageObject;//消息全局对象
}

//tableView三件套

@property (nonatomic,strong)UITableView *bigPicTableView;
@property (nonatomic,strong)NSMutableArray *CommendArray;//评论的数组(每一次从服务器上获取评论数组,判断是否为空,为空就代表没有评论,就必须创建评论,然后addobject进这个数组，然后在上传给服务器,不为空的话直接add进这个数组就好了)
@property (nonatomic,strong)NSMutableArray *commendDataArray;//装评论模型的数组
@property (nonatomic,strong)NSMutableArray *cellHeightArray;//一个专门存储cellHeight的数组
@end

@implementation bigPicViewController
#pragma mark - 懒加载
- (NSMutableArray *)commendDataArray{
    if (!_commendDataArray) {
        _commendDataArray = [NSMutableArray new];
    }
    return _commendDataArray;
}
//评论里面包的是字典
- (NSMutableArray *)CommendArray{
    if (!_CommendArray) {
        _CommendArray = [NSMutableArray new];
    }else{
        [self sortArray:_CommendArray];//非首次的话就排序
    }
    return _CommendArray;
}
- (NSMutableArray *)cellHeightArray{
    if (!_cellHeightArray) {
        _cellHeightArray = [NSMutableArray new];
    }
    return _cellHeightArray;
}
#pragma mark - 评论按时间进行排序
- (void)sortArray:(NSMutableArray *)Array{
    NSSortDescriptor *desc = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:YES];
    [Array sortUsingDescriptors:@[desc]];
}
#pragma mark - 生命周期

- (void)viewDidLoad {
    [super viewDidLoad];
    [self preferData];
    [self createUI];
    //先从服务器中获取当前ObjectId的评论
    __weak typeof(self)weakSelf = self ;
    AVQuery *query = [AVQuery queryWithClassName:@"Commend"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        for (AVObject *object in objects) {
            //找到了
        
            if ([[object valueForKey:@"ID"]isEqualToString:self.objectID]) {
                [weakSelf.CommendArray addObjectsFromArray:[object valueForKey:@"Commend"]];
                
            }
        }
        for (NSDictionary *dict in self.CommendArray) {
            commendModel *model = [[commendModel alloc]initWithDictionary:dict];
            [self.commendDataArray addObject:model];
          
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.bigPicTableView reloadData];
        });
    
    }];
   
    _MessageObject = [[AVObject alloc]initWithClassName:@"message"];
  
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - UI搭建
- (void)createUI{
    
    //导航条
    //设置navgationBar
    UIBarButtonItem *left = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(onClicked)];
    [self.navigationItem setLeftBarButtonItem:left];
    self.title = @"正文";
    self.navigationController.navigationBar.translucent = NO ;
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:86/255.0f green:202/255.0f blue:255/255.0f alpha:0.5]];
    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    //tableView
    _bigPicTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, LC_WIDTH, LC_HEIGHT - 34 - 64 )];
  
  
 
    [self.view addSubview:_bigPicTableView];
   
    _bigPicTableView.showsVerticalScrollIndicator = NO;
    _bigPicTableView.delegate = self ;
    _bigPicTableView.dataSource = self ;
    //取消横线
    [_bigPicTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    //发表评论
    _commendText = [UITextView new];
    _commendText.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:_commendText];
    
    _commendText = [[UITextView alloc]initWithFrame:CGRectMake(0, LC_HEIGHT - 64 - 34  , LC_WIDTH, 34)];
    [self.view addSubview:_commendText];
    _commendText.backgroundColor = [UIColor lightGrayColor];
    [_commendText setReturnKeyType:UIReturnKeyDone];
    _commendText.delegate = self ;
    _commendText.text = @"评论";
    _commendText.textColor = [UIColor whiteColor];
    _commendText.layer.cornerRadius = 5 ;
    _commendText.layer.masksToBounds = YES ;
    //监听键盘消失和出现
    //show
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillShowNotification object:nil];
    //hide
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardHide:) name:UIKeyboardWillHideNotification object:nil];
    //4.添加单击手势
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard)];
    [_bigPicTableView addGestureRecognizer:tap];
    
    
}
#pragma mark - 准备数据
- (void)preferData{
    [AVFile getFileWithObjectId:self.objectID withBlock:^(AVFile *file, NSError *error) {
        tinyDataModel *model = [[tinyDataModel alloc]initWithDict:  [AVFile fileWithDictionary:file]];
        tinyFrameModel *frameModel = [tinyFrameModel new];
        frameModel.dataModel = model ;
        self.dataModel = model ;
        self.frameModel = frameModel ;
        
    }];

}
#pragma mark - 注销观察者
- (void)dealloc{
   
    //键盘弹起的观察者
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - textView协议
- (void)textViewDidBeginEditing:(UITextView *)textView{
    textView.text = @"";
}
//输入完成之后显示,并且上传到服务器
- (void)textViewDidEndEditing:(UITextView *)textView{
    
    //先删除评论数组重复的东西
    [self.CommendArray removeAllObjects];
    //获取用户头像
    AVFile *iconFile = [[AVUser currentUser] objectForKey:@"iconImage"] ;
    //方崩溃，因为如果键值不存在解析的话，会发生崩溃
    if (iconFile) {
        //获取头像信息字典
        NSDictionary *fileDict =  [AVFile fileWithDictionary:iconFile];
        NSDate *date = [NSDate new];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat = @"MM-dd HH时";//MM月-DD日 HH时MM分
        NSString *timeString = [formatter stringFromDate:date];
        
        //评论是数组,数组里面装字典
        NSDictionary *dict = @{@"name":[AVUser currentUser].username,
                               @"iconImage":fileDict[@"url"],
                               @"compent":_commendText.text,
                               @"time":timeString,
                               
                               };
        [self.CommendArray addObject:dict];
        _iconUrl = fileDict[@"url"];//保存头像
}
    
    NSLog(@"开始的时候%@",self.commendDataArray);
    //获取评论
    [self requestDataWithObjectId:self.objectID];
    
    
}
//当遇到换行是,默认发送
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        
        [textView resignFirstResponder];
    }
    return YES;
}
#pragma mark - tableView协议
//制定为2个section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
//为每一个section分配cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //多一个评论的cell
    if (section == 0) {
        return 1;
    }else{
        return self.commendDataArray.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //单独第一行用一种cell
    if (indexPath.section == 0) {
        
        tintyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[tintyCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        }
        cell.dataModel = self.dataModel;
        cell.frameModel = self.frameModel;
        
        return cell;
        
        //其他的就是评论cell
    }else{
        commendTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cCell"];
        if (!cell) {
            cell = [[commendTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cCell"];
            
        }
        cell.model = self.commendDataArray[indexPath.row];
       
        return  cell;
    }
}
//长度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        return  [self.frameModel cellHeight];
    }else{
        return 90;
    }
 
}
//footer的长度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return 20 ;
    }else{
        return  0;
    }
}
#pragma mark - 点击事件
- (void)onClicked{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 数据相关(获取评论)
- (void)requestDataWithObjectId:(NSString *)objectID{
    
    __weak typeof(self)weakSelf = self ;
  //先从file表单里面找到该说说
    [AVFile getFileWithObjectId:objectID withBlock:^(AVFile *file, NSError *error) {
        //解析数据
        NSDictionary *dicts = [AVFile fileWithDictionary:file];
        _username = dicts[@"metaData"][@"username"] ;//获取到主键
        }];
    
    
    //先从服务器找到ID
    AVQuery *query = [AVQuery queryWithClassName:@"Commend"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        //        //如果整个评论的表单都为空的话，创建一个字段先
        if (objects.count == 0) {
            AVObject *object = [[AVObject alloc]initWithClassName:@"Commend"];
            [object setObject:weakSelf.objectID forKey:@"ID"];
            [object setObject:weakSelf.CommendArray forKey:@"Commend"];
            [object saveInBackground];
            
           
            //说说的ID
            [_MessageObject setObject:objectID forKey:@"talkID"];
            //描述
            [_MessageObject setObject:[NSString stringWithFormat:@"%@评论了你的说说,快去看看吧",[AVUser currentUser].username] forKey:@"desc"];
            [_MessageObject setObject:[AVUser currentUser].username forKey:@"requestName"];
            [_MessageObject setObject:_iconUrl forKey:@"url"];
            [_MessageObject setObject:_username forKey:@"ID"];
            
            [_MessageObject saveInBackground];

        }
        int i =0;
        for (AVObject  *tObj in objects) {
        
            //根据ID找到属于本条说说的评论
            if ([[tObj valueForKey:@"ID" ] isEqualToString:objectID]) {
             
                //如果还未有评论的话
                NSArray *array = [tObj valueForKey:@"Commend"];
                
                if (array.count == 0) {
                    //创建评论
                    [tObj setObject:weakSelf.objectID forKey:@"ID"];
                    [tObj setObject:weakSelf.CommendArray forKey:@"Commend"];
                    //保存
                    [tObj saveInBackground];
                    //============创建消息====================
                  
                    
                    //说说的ID
                    [_MessageObject setObject:objectID forKey:@"talkID"];
                    //描述
                    [_MessageObject setObject:[NSString stringWithFormat:@"%@评论了你的说说,快去看看吧",[AVUser currentUser].username] forKey:@"desc"];
                    [_MessageObject setObject:[AVUser currentUser].username forKey:@"requestName"];
                    [_MessageObject setObject:_iconUrl forKey:@"url"];
                    [_MessageObject setObject:_username forKey:@"ID"];
                    
                    [_MessageObject saveInBackground];
                   
                    
                    break;
                }
                else{
                    //如果有评论的话,更新评论
                    [weakSelf.CommendArray addObjectsFromArray:[tObj valueForKey:@"Commend"]];
                    [tObj setObject:weakSelf.CommendArray forKey:@"Commend"];
                    //保存
                    [tObj saveInBackground];
                    
                    //============创建消息====================
                    
                    
                    //说说的ID
                    [_MessageObject setObject:objectID forKey:@"talkID"];
                    //描述
                    [_MessageObject setObject:[NSString stringWithFormat:@"%@评论了你的说说,快去看看吧",[AVUser currentUser].username] forKey:@"desc"];
                    [_MessageObject setObject:[AVUser currentUser].username forKey:@"requestName"];
                    [_MessageObject setObject:_iconUrl forKey:@"url"];
                    [_MessageObject setObject:_username forKey:@"ID"];
                    
                    [_MessageObject saveInBackground];
                    break;
                }
            }
            i ++;
            //评论表单里面没有这个ID的评论字段，创建出来
            if(i == objects.count ) {
                
                AVObject *object = [[AVObject alloc]initWithClassName:@"Commend"];
                [object setObject:weakSelf.objectID forKey:@"ID"];
                
                //创建评论
                [object setObject:weakSelf.CommendArray forKey:@"Commend"];
                [object saveInBackground];
                
                //============创建消息====================
                
                //说说的ID
                [_MessageObject setObject:objectID forKey:@"talkID"];
                //描述
                [_MessageObject setObject:[NSString stringWithFormat:@"%@评论了你的说说,快去看看吧",[AVUser currentUser].username] forKey:@"desc"];
                [_MessageObject setObject:[AVUser currentUser].username forKey:@"requestName"];
                [_MessageObject setObject:_iconUrl forKey:@"url"];
                [_MessageObject setObject:_username forKey:@"ID"];
                
                [_MessageObject saveInBackground];

                break;
            }
            
        }
        
        //先清空评论
        [weakSelf.commendDataArray removeAllObjects];
        //再把当前服务器上的评论赋值给本地评论数据源数组
        for (NSDictionary *dic in weakSelf.CommendArray) {
            commendModel *model = [[commendModel alloc]initWithDictionary:dic];
            [weakSelf.commendDataArray addObject:model];
        }
       
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.bigPicTableView reloadData];
        });
}];
  
    
}
#pragma mark - 消息中心
- (void)keyBoardShow:(NSNotification *)notification{
    
    //获取键盘的frame
    CGRect rect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //拿到键盘的高度
    float keyboardHeight = rect.size.height;
    
    //让textfiled和tableView随着键盘上移
    [UIView animateWithDuration:0.3f animations:^{
        
        _commendText.frame = CGRectMake(0, LC_HEIGHT  - keyboardHeight - 64 -34 , _commendText.frame.size.width, 34);
        
        _bigPicTableView.frame = CGRectMake(0, 0 - keyboardHeight , _bigPicTableView.frame.size.width, _bigPicTableView.frame.size.height );
        
    }];
    NSLog(@"%ld",(unsigned long)self.CommendArray.count);
    //将tableView滚动到最下面
    //此时如果数据源数组不为0的情况下
    if (self.commendDataArray.count > 0) {
        NSLog(@"1111");
        NSIndexPath *path = [NSIndexPath indexPathForRow:self.commendDataArray.count - 1 inSection:1];
        [_bigPicTableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }

    
}

- (void)hideKeyBoard{
    
    [_commendText resignFirstResponder];
}

//键盘消失的响应
- (void)keyBoardHide:(NSNotification *)notification{
    
    [UIView animateWithDuration:0.3f animations:^{
        
        _commendText.frame = CGRectMake(0, self.view.frame.size.height - 34, self.view.frame.size.width, 34);
        
        _bigPicTableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 34 );
    }];
    
}
@end
